#!/usr/bin/env python
# -*- coding: utf-8 -*-

from gevent import monkey
monkey.patch_all()

from traceback import format_exc
from werkzeug.wrappers import Request, Response
from werkzeug.exceptions import HTTPException, NotFound, \
        MethodNotAllowed, BadRequest
from utils import url_map, logger
from server import g_server


def xyf_customtag(environ, start_response):
    request = Request(environ)
    adapter = url_map.bind_to_environ(environ)
    try:
        endpoint, values = adapter.match()
        response = getattr(g_server, endpoint)(request, **values)
    except (NotFound, MethodNotAllowed, BadRequest), e:
        response = e
    except HTTPException, e:
        response = e
    except:
        response = Response('Uncatched Error', status=500)
        logger.debug('app uncatched error, exception:%s', format_exc())
    return response(environ, start_response)
